package cn.stimd.spring.context.event;

import org.springframework.core.ResolvableType;

/**
 * Created by Stimd
 * 项目地址：https://gitee.com/stimd/spring-wheel
 * 公众号：Java编程探微
 */
public class GenericApplicationListenerAdapter implements GenericApplicationListener{
    //真正的监听器对象
    private final ApplicationListener<ApplicationEvent> delegate;
    //监听器类的泛型类型，即ApplicationListener<E extends ApplicationEvent>中E的实际类型
    private final ResolvableType declaredEventType;


    public GenericApplicationListenerAdapter(ApplicationListener<?> delegate) {
        this.delegate = (ApplicationListener<ApplicationEvent>) delegate;
        this.declaredEventType = resolveDeclaredEventType(this.delegate.getClass());
    }

    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        this.delegate.onApplicationEvent(event);
    }

    @Override
    public boolean supportsEventType(ResolvableType eventType) {
        return (this.declaredEventType == null || this.declaredEventType.isAssignableFrom(eventType));
    }

    @Override
    public boolean supportsSourceType(Class<?> sourceType) {
        return true;
    }


    static ResolvableType resolveDeclaredEventType(Class<?> listenerType) {
        ResolvableType resolvableType = ResolvableType.forClass(listenerType).as(ApplicationListener.class);
        return (resolvableType.hasGenerics() ? resolvableType.getGeneric() : null);
    }
}
